<template>
  <!-- 标签录入组件 -->
  <div :style="showCrosswise? 'display:flex':''">
    <div v-if="!disabled" class="textLine customerTag">
      <el-button class="button-new-tag" size="small" @click="title = '添加标签', handleClickLabel()">
        <svg-icon icon-class="add" />
        添加标签
      </el-button>
    </div>
    <!-- <div class="textLine" style="max-width: 300px;overflow: scroll;"> -->
    <div class="textLine" :style="{ maxWidth }">
      <div class="essInfo">
        <!--  @click="!disabled && tabEdit(item, i)" -->
        <el-tag v-for="(item, i) in tagGroup" :key="i" :closable="!disabled" style="margin-bottom: 8px"
          @close="handleCloseLabel(item, i)" class="el-tag-tab-group" :style="showCrosswise? 'margin-left:10px':''">
          {{ item.groupName + '：' + item.tagName || item.tag }}
        </el-tag>
      </div>

      <!-- <div v-for="(item, i) in tagGroup" :key="i">
        <el-tag v-for="(tag, index) in item.tagName" :key="index" :closable="!disabled" style="margin-bottom: 8px"
          @close="handleCloseLabel(item, i)" @click="!disabled && tabEdit(item, i)">
          {{ item.groupName + '：' + item.tagName || item.tag }}
        </el-tag>
      </div> -->
    </div>

    <!--  @close="staffClose" -->
    <el-dialog :title="title" :visible.sync="staffDialog" :destroy-on-close="destroyOnClose" :close-on-click-modal="false"
      :close-on-press-escape="false" append-to-body width="500px">
      <el-form label-width="80px" :model="tagGroupItem" ref="tagGroupItem" :rules="rules">
        <el-form-item label="标签组名" prop="groupName">
          <!-- <el-input v-model.trim="tagGroupItem.groupName" autocomplete="off" placeholder="请输入标签组名"></el-input> -->
          <!--  @select="handleSelect" -->
          <el-autocomplete v-model.trim="tagGroupItem.groupName" :fetch-suggestions="querySearch" @blur="groupNameBlur"
            :trigger-on-focus="false" placeholder="请输入标签组名" style="width:100%"></el-autocomplete>
        </el-form-item>
        <el-form-item label="标签" prop="tagName">
          <!-- <el-input v-model.trim="tagGroupItem.tagName" autocomplete="off" placeholder="请输入标签"></el-input> -->

          <el-autocomplete v-model="tagGroupItem.tagName" :fetch-suggestions="querySearchTagName" placeholder="请输入内容"
            style="width:100%"></el-autocomplete>

        </el-form-item>
        <el-form-item label="是否覆盖" prop="isMulti">
          <el-radio-group v-model="tagGroupItem.isMulti" :disabled="isMultiD">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="handleAddTag" :loading="loading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import { getLabelSelectList, labelCheck } from "@/api/label";
export default {
  name: 'tagGroup',
  props: {
    maxWidth: {
      type: String,
      default: '100%'
    },
    tagGroup: {
      type: Array,
      default: () => []
    },
    showCrosswise: {
      type: Boolean,
      default: false,
    },
    rules: {
      type: Object,
      default: () => {
        return {
          groupName: [
            { required: true, message: '请输入标签组名', trigger: ['blur', 'change'] }
          ],
          tagName: [
            { required: true, message: '请输入标签', trigger: ['blur', 'change'] },
            { pattern: /^[^，,]*$/, message: '请不要输入逗号', trigger: ['blur', 'change'] }
          ],
        }
      }
    },
    destroyOnClose: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      isMultiD: false,
      title: '添加标签',
      tagGroupItem: {
        isMulti: 0,
        groupName: "",
        tagName: "",
        weTagGroupId: null,
        tag: null
      },
      staffDialog: false,
      loading: false,
      index: -1,
      results: [],
      tagNameArr: [],
    }
  },
  watch: {
    staffDialog(val) {
      if (!val) {
        this.isMultiD = false;
        this.index = -1
        this.resetTagGroupItem()
      }
    }
  },
  methods: {
    // 搜索框
    querySearch(queryString, cb) {
      // console.log('queryString', queryString);
      if (this.isMultiD) this.isMultiD = false
      this.results = [
        // {
        //   "isMulti": 0,
        //   "groupName": "111",
        //   "tagName": "124124",
        //   "weTagGroupId": null,
        //   "tag": null
        // },
        // {
        //   "isMulti": 0,
        //   "groupName": "123123",
        //   "tagName": "144214",
        //   "weTagGroupId": null,
        //   "tag": null
        // }
      ]
      if (queryString) {
        getLabelSelectList(queryString).then(res => {
          if (res.code === 200) this.results = res.data
        }).finally(() => {
          cb(this.results)
          // console.log('results', results);
        })
      }
    },
    querySearchTagName(queryString, cb) {
      cb(this.tagNameArr)
    },
    // 失去焦点，判断输入的值是否与获取的 results 有重复的
    groupNameBlur() {
      setTimeout(() => {
        // console.log('this.tagGroupItem.groupName', this.tagGroupItem.groupName);
        let i = 0
        this.tagNameArr = []
        this.results.forEach(item => {
          if (i == 0 && item.value == this.tagGroupItem.groupName) {
            this.tagNameArr = item.tagNameList || []
            this.handleSelect(item)
            i++;
          }
        })
      }, 200)
    },
    // 选中后触发事件
    handleSelect(item) {
      // console.log('this.tagGroupItem.groupNameS', this.tagGroupItem.groupName);
      this.tagGroupItem.isMulti = item.isMulti || 0
      this.isMultiD = true;
    },
    handleAddTag() {
      this.$refs.tagGroupItem.validate((valid) => {
        if (valid) {
          if (!this.tagGroup) this.tagGroup = []
          // if (this.index > -1) {
          //   this.tagGroup[this.index] = this.tagGroupItem;
          //   this.index = -1
          // } else {
          if (this.tagGroup.some(item => item.groupName == this.tagGroupItem.groupName && item.tagName == this.tagGroupItem.tagName)) {
            return this.$message.error('该标签组已存在')
          }

          // }
          // 调接口判断标签是否通过后端校验
          this.loading = true
          labelCheck(this.tagGroupItem).then(res => {
            if (res.code == 200) {
              let tagGroup = this.tagGroup.concat([this.tagGroupItem])
              let sottArr = tagGroup.sort((a, b) => a.isMulti - b.isMulti)
              let map = new Map()
              console.log('tagGroup', tagGroup);

              if (tagGroup.length > 1) {
                for (let index = 0; index < tagGroup.length; index++) {
                  const item = sottArr[index];
                  if (index == 0 || !map[item.groupName]) map[item.groupName] = item
                  else if (index > 0) {
                    if (map[item.groupName].isMulti == 0 || item.isMulti == 0) return this.$message.error(`标签组名(${item.groupName})存在冲突，请检查`)
                  }
                  console.log('map', map);
                }
              }

              this.tagGroup.push(JSON.parse(JSON.stringify(this.tagGroupItem)))
              this.$emit('change', this.tagGroup)
              this.staffDialog = false
            }
          }).finally(() => this.loading = false)
        }
      })
    },

    // handleAddTag() {
    //   this.$refs.tagGroupItem.validate((valid) => {
    //     if (valid) {
    //       if (!this.tagGroup) this.tagGroup = []
    //       if (this.index > -1) {
    //         // 编辑，功能已移除
    //         this.tagGroup[this.index] = this.tagGroupItem;
    //         this.index = -1
    //       } else {
    //         // 新增
    //         // 如果是单选标签，覆盖之前标签组

    //         if (this.tagGroupItem.isMulti == 1 && this.tagGroup.some(item => item.groupName == this.tagGroupItem.groupName && item.tagName == this.tagGroupItem.tagName)) {
    //           return this.$message.error('该标签组已存在')
    //         } else if (this.tagGroupItem.isMulti == 0 && this.tagGroup.some(item => item.groupName == this.tagGroupItem.groupName)) {
    //           let ns = []
    //           this.tagGroup.forEach((item, n) => item.groupName == this.tagGroupItem.groupName && (item.tagName = this.tagGroupItem.tagName) && ns.push(n))
    //           ns.forEach((n, index) => this.handleCloseLabel(n, n))
    //           this.$emit('change', this.tagGroup)
    //           this.staffDialog = false
    //         } else this.tagGroup.push(JSON.parse(JSON.stringify(this.tagGroupItem)))
    //       }
    //       this.$emit('change', this.tagGroup)
    //       this.staffDialog = false
    //     }
    //   })
    // },
    tabEdit(item, i) {
      this.tagGroupItem = JSON.parse(JSON.stringify(item))
      this.title = '编辑标签'
      this.index = i
      this.handleClickLabel()
    },
    handleClickLabel() {
      this.staffDialog = true
      // console.log('tagGroupItem.isMulti', this.tagGroupItem.isMulti);
    },
    handleCloseLabel(item, i) {
      this.tagGroup.splice(i, 1)
    },
    resetTagGroupItem() {
      this.tagGroupItem = {
        isMulti: 0,
        groupName: "",
        tagName: "",
        weTagGroupId: null,
        tag: null
      }
    },
  },
  model: {
    prop: 'tagGroup',
    event: 'change'
  }
}
</script>

<style lang="scss" scoped>
.el-tag-tab-group:nth-of-type(2) {
  margin-left: 0 !important;
}

.el-tag-tab-group:nth-of-type(1) {
  margin-right: 10px;
}
</style>
